/**
 * Create by CaoWenjian
 *
 * @copyRight: 2018
 **/
package com.bjboot.caocao.system.controller;

import com.bjboot.caocao.common.config.Constant;
import com.bjboot.caocao.common.exception.BJException;
import com.bjboot.caocao.common.utils.MD5Utils;
import com.bjboot.caocao.common.utils.PageUtils;
import com.bjboot.caocao.common.utils.Query;
import com.bjboot.caocao.common.utils.Result;
import com.bjboot.caocao.system.annotation.BJLog;
import com.bjboot.caocao.system.domain.DeptDO;
import com.bjboot.caocao.system.domain.RoleDO;
import com.bjboot.caocao.system.domain.Tree;
import com.bjboot.caocao.system.domain.UserDO;
import com.bjboot.caocao.system.pojo.UserPwdPojo;
import com.bjboot.caocao.common.service.DictService;
import com.bjboot.caocao.system.service.RoleService;
import com.bjboot.caocao.system.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 *@Description 用户相关的控制器
 *@Author 操文健
 *@Date 2018-09-05 下午3:59
 *@Version 1.0
 **/
@RequestMapping("/sys/user")
@Controller
public class UserController extends UserBaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    // 前缀
    private String prefix="system/user" ;

    @Autowired
    private DictService dictService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /*#############################index主界面个人模块【start】#######################################*/
    /**
     * 个人信息的展示修改，界面右上方直接跳转的界面
     * @param model
     * @return
     */
    @ApiOperation(value = "个人界面Module")
    @GetMapping("/personal")
    String personal(Model model) {
        logger.debug("进入控用户查询信息的controller....");
        UserDO userDO  = userService.getUserById(getUserId());
        // 设置界面的属性
        model.addAttribute("hobbyList",dictService.getHobbyList(userDO));
        model.addAttribute("sexList",dictService.getSexList());
        model.addAttribute("user",userDO);
        return prefix + "/personal";
    }

    /**
     * 更新用户的信息
     * @param user
     * @return
     */
    @ApiOperation(value = "更新个人用户信息")
    @RequiresPermissions("sys:user:edit")
    @BJLog("更新用户基本信息")
    @PostMapping("/updatePeronal")
    @ResponseBody
    Result updatePeronal(UserDO user) {
        if (userService.updatePersonal(user)) {
            return Result.ok();
        }
        return Result.error();
    }

    /**
     * 个人用户更改密码
     * @param userPojo
     * @return
     */
    @ApiOperation(value = "个人更改用户密码")
    @BJLog("个人更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    Result resetPwd(UserPwdPojo userPojo) {
        try{
            userService.resetPwd(userPojo,getUser());
            return Result.ok();
        }catch (BJException e){
            return Result.error(1,e.getMsg());
        }

    }

    /**
     * 上传用户的头像信息
     * @param file
     * @param avatar_data
     * @param request
     * @return
     */
    @ApiOperation(value = "上传用户头像图片")
    @ResponseBody
    @PostMapping("/uploadImg")
    Result uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
        Map<String, Object> result = null;
        try {
            result = userService.updatePersonalImg(file, avatar_data, getUserId());
        } catch (Exception e) {
            return Result.error("更新图像失败！");
        }
        if(result!=null && result.size()>0){
            return Result.ok(result);
        }else {
            return Result.error("更新图像失败！");
        }
    }

    /*#############################index主界面个人模块【end】#######################################*/

    /**
     * 访问用户管理界面
     * @param model
     * @return
     */
    @ApiOperation(value="访问用户主页")
    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        return prefix + "/user";
    }

    @ApiOperation(value = "查询用户列表信息")
    @GetMapping("/list")
    @ResponseBody
    PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<UserDO> sysUserList = userService.list(query);
        int total = userService.count(query);
        PageUtils pageUtil = new PageUtils(sysUserList, total);
        return pageUtil;
    }

    @ApiOperation(value = "返回用户查询模板")
    @RequiresPermissions("sys:user:add")
    @BJLog("添加用户")
    @GetMapping("/add")
    String add(Model model) {
        List<RoleDO> roles = roleService.list();
        model.addAttribute("roles", roles);
        return prefix + "/add";
    }

    @ApiOperation(value = "返回编辑用户列表")
    @RequiresPermissions("sys:user:edit")
    @BJLog("编辑用户")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        UserDO userDO = userService.get(id);
        model.addAttribute("user", userDO);
        List<RoleDO> roles = roleService.list(id);
        model.addAttribute("roles", roles);
        return prefix+"/edit";
    }

    @ApiOperation(value = "保存用户信息")
    @RequiresPermissions("sys:user:add")
    @BJLog("保存用户")
    @PostMapping("/save")
    @ResponseBody
    Result save(UserDO user) {
        user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
        if (userService.save(user) > 0) {
            return Result.ok();
        }
        return Result.error();
    }

    @ApiOperation(value = "更新用户信息")
    @RequiresPermissions("sys:user:edit")
    @BJLog("更新用户")
    @PostMapping("/update")
    @ResponseBody
    Result update(UserDO user) {
        if (userService.update(user) > 0) {
            return Result.ok();
        }
        return Result.error();
    }

    @ApiOperation(value = "删除用户")
    @RequiresPermissions("sys:user:remove")
    @BJLog("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    Result remove(Long id) {
        if (userService.remove(id) > 0) {
            return Result.ok();
        }
        return Result.error();
    }

    @ApiOperation(value = "批量删除用户")
    @RequiresPermissions("sys:user:batchRemove")
    @BJLog("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    Result batchRemove(@RequestParam("ids[]") Long[] userIds) {
        int r = userService.batchremove(userIds);
        if (r > 0) {
            return Result.ok();
        }
        return Result.error();
    }

    @ApiOperation(value = "判断用户是否存在")
    @PostMapping("/exit")
    @ResponseBody
    boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exit(params);
    }

    /**
     * 用户管理界面更新用户密码，
     * @param userId
     * @param model
     * @return
     */
    @ApiOperation(value = "更新密码界面跳转")
    @RequiresPermissions("sys:user:resetPwd")
    @BJLog("提交shenqing 更改用户密码")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {
        // 组装数据跳转到对应到密码更新界面
        UserDO userDO = new UserDO();
        userDO.setUserId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    /**
     * 管理员直接重置密码
     * @param userPojo
     * @return
     */
    @ApiOperation(value = "Admin更新密码")
    @RequiresPermissions("sys:user:resetPwd")
    @BJLog("admin提交重置用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    Result adminResetPwd(UserPwdPojo userPojo) {
        try{
            userService.adminResetPwd(userPojo);
            return Result.ok();
        }catch (Exception e){
            return Result.error(1,e.getMessage());
        }

    }

    @GetMapping("/tree")
    @ResponseBody
    public Tree<DeptDO> tree() {
        Tree<DeptDO> tree = new Tree<DeptDO>();
        tree = userService.getTree();
        return tree;
    }

    @GetMapping("/treeView")
    String treeView() {
        return  prefix + "/userTree";
    }

}
